<!--
* description: 新增编辑-网点备件清单维护
* author: xiaochengzuan
* createdDate: 2021-3-2
-->
<template>
  <section class="editBigAreaInfo">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible="curPopupsVisible"
      width="70%"
      @close="closeEdit"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />

      <div class="filter-container filter-params">
        <el-row ref="vailComponentList" :gutter="26">
          <one-table-template
            ref="multipleTable"
            :key="oneTableKey"
            :dynamic-buttons="tableButtonsQuery"
            :dynamic-components="tableComponents"
            :dynamic-api-config="apiConfig"
            :dynamic-table-cols="tableCols"
            :dynamic-form-fields="formField"
            :dynamic-is-show-select="false"
            :dynamic-is-init-table="false"
            :dynamic-api-style="'restful'"
          />
          <!-- <component
            :is="comp.component"
            v-for="comp in tableComponents.filter(o => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire+ comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds || ''"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :is-require="comp.isRequire"
            :is-mul="comp.isMul"
            :span="comp.span || 8"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :date-options-type="comp.dateOptionsType"
            @changeCode="getComponentCode"
          /> -->
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :icon="comp.icon"
          @click="comp.clickEvent"
        >{{ comp.text }}</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from '@/components/mixins/formMixins'
import { orgApis } from '@/api/pabasicdataapi'

import OneTableTemplate from '@/components/templates/oneTable'

export default {
  components: {
    dialogHeader: () => import('@/components/dialogHeader'),
    mixButton: () => import('@/components/basicComponent/mixButton'),
    OneTableTemplate
  },

  // 组件混入对象
  mixins: [formMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: { type: Object, default: function() { return {} } }
  },

  data() {
    const viewPageCode = 'bigAreaInfo-edit'
    return {
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => this.save(),
          text: this.$t('sys.button.save') /* 保存*/,
          position: 'right'
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          icon: 'iconfont  icon-cancel',
          clickEvent: () => this.close(),
          text: this.$t('sys.button.cancel') // 取消
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '备件编码：',
              codeField: 'partNo',
              component: () => import('@/components/org/commonInput/indexprepend'),
              dataToObject: {
                prepend: this.$store.state.user.orgInfo.DLR_CODE
              },
              isShow: true,
              disabled: true,
              isRequire: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey111',
              labelName: '备件编码：',
              codeField: 'partNo',
              component: () => import('@/components/org/commonInput'),
              isShow: false,
              isRequire: true,
              disabled: 'true',
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey2',
              labelName: '备件名称：',
              codeField: 'partName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              isMust: true,
              span: 8,
            },
            {
              compKey: 'compKey3',
              labelName: '供应商：',
              codeField: 'supplierId',
              textField: 'supplierShortName',
              otherField: 'supplierCode',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              isRequire: true,
              customObj: {
                showType: 'text'
              },
              dataToObject: {
                // 控制弹窗页面 搜索 网格 元素
                oFields: 'supplierId,supplierShortName',
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '供应商编码：',
                    codeField: 'supplierCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '供应商名称：',
                    codeField: 'supplierShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'supplierCode',
                    label: '供应商编码'
                  },
                  {
                    prop: 'supplierShortName',
                    label: '供应商名称'
                  }
                ],
                formField: {
                  supplierCode: '',
                  supplierShortName: '',
                  isEnable: '1'
                },
                returnField: {
                  prop: 'supplierCode',
                  label: '供应商编码'
                },
                api: {
                  APIUrl: '/mp/e3sh/spareparts/outsourcedSparePartsService/queryOutsourcedSpareParts.do'
                }
              },
              span: 8,
            },
            {
              compKey: 'compKey4',
              labelName: '维修类型: ',
              codeField: 'partRepairType',
              customObj: {
                api: orgApis.sparePartsListQuerycategoryselect
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              span: 8,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '适用车型：',
              codeField: 'carConfigIdList',
              textField: 'carConfigCn',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              dataToObject: {
                oFields: 'carConfigCode,carConfigCn',
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '车型编码：',
                    codeField: 'carConfigCode',
                    isMul: false,
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '车型名称：',
                    codeField: 'carConfigCn',
                    isMul: false,
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'carSeriesCode',
                    label: '车系编码'
                  },
                  {
                    prop: 'carSeriesCn',
                    label: '车系名称'
                  },
                  {
                    prop: 'carConfigCode',
                    label: '车型编码'
                  },
                  {
                    prop: 'carConfigCn',
                    label: '车型名称'
                  }
                ],
                formField: {
                  carConfigCode: '',
                  carConfigCn: ''
                },
                returnField: {
                  prop: 'carConfigCode',
                  label: '车型编码'
                },
                api: { APIUrl: 'mp/e3sh/spareparts/basic/partPriceQueryService/queryCarConfigCodes.do', ServiceCode: 'queryCarConfigCodes' },
              },
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey6',
              labelName: '订货开关: ',
              codeField: 'isOrder',
              component: () => import('@/components/org/LookupValue'),
              type: 'dropdownList',
              span: 8,
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '打开' },
                { statusId: '0', statusText: '关闭' }
              ],
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey6',
              labelName: '备件单位：',
              codeField: 'unit',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              isMust: true,
              span: 8,
            },

            {
              compKey: 'compKey7',
              labelName: '网点价：',
              codeField: 'outletPrice',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              validrule: {
                // 保留一到两位小数
                isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
                resectMessage: {
                  isformat: '请输入正确的网点价格!'
                }
              },
              isMust: true,
              span: 8,
            },

            {
              compKey: 'compKey8',
              labelName: '用户价：',
              codeField: 'userPrice',
              component: () => import('@/components/org/commonInput'),
              isRequire: true,
              validrule: {
                // 保留一到两位小数
                isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
                resectMessage: {
                  isformat: '请输入正确的价格!'
                }
              },
              span: 8,
              isMust: true
            },

            {
              compKey: 'compKey9',
              labelName: '最小采购包装：',
              codeField: 'minPurchasePage',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              validrule: {isInteger: true},
              span: 8,
              isMust: true
            },

            {
              compKey: 'compKey10',
              labelName: '最小销售包装：',
              codeField: 'minSalesPage',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              validrule: {isInteger: true},
              isRequire: true,
              span: 8,
              isMust: true
            },

            {
              compKey: 'compKey11',
              labelName: '标准库存量：',
              codeField: 'standardStock',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              validrule: {isInteger: true},
              isMust: true,
              span: 8,
              // disabled: true
            },
            {
              compKey: 'compKey12',
              labelName: '安全库存：',
              codeField: 'safetyStock',
              validrule: {isInteger: true},
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              span: 8,
              isMust: true
            },
            {
              compKey: 'compKey13',
              labelName: '备注：',
              codeField: 'remark',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 16
            }
          ],

      // 标题
      textMap: {
        edit: '网点备件信息修改',
        add: '网点备件信息新增'
      },

      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(this, {

        partNo: '',
        partName: '',
        partRepairType: '',
        carConfigIdList: '',
        carConfigCn: '',
        isOrder: '',
        standardStock: '0',
        unit: '',
        outletPrice: '',
        userPrice: '',
        minPurchasePage: '',
        minSalesPage: '',
        safetyStock: '0',
        supplierId: '',
        supplierShortName: '',
        supplierCode: '',
        areaRemark: '',
        updateControlId: '',
        remark: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    }
  },
  created() {
    this.execCreated()
    this.setDisable()
    this.tableComponents.find(o => o.compKey === 'compKey1').isShow = this.popupsState === 'add'
    this.tableComponents.find(o => o.compKey === 'compKey111').isShow = this.popupsState === 'edit'
    if (this.popupsState === 'add') {
      this.getpartcode()
    }
  },
  methods: {
    async getpartcode() {
      const apiUrl = '/mp/e3sh/spareparts/listMaintenanceService/queryPartNoCode.do'
      const variables = {}
      let response
      try {
        response = await this.$requestAPI({ apiUrl, variables })
      } catch (e) { return }
      if (response.result === '1') {
        // 赋值
        this.formField.partNo = response.rows[0].partNo
      } else {
        this.$message(response.msg || '备件编码获取失败！')
      }
    },
    // 关闭弹窗
    // handleClose(done) {
    //   this.$confirm('还未保存，确认关闭窗口？')
    //     .then(_ => {
    //       this.$emit('update:curPopupsVisible', false)
    //       done()
    //     })
    //     .catch(_ => {})
    // },
    closeEdit() {
      this.$emit('update:popups-visible', false)
    },
    // 新增/编辑保存按钮
    save() {
      const that = this
      this.$utils.validataMoth(this, 'validpage')
      if (this.valid) {
        if (that.popupsState === 'edit') {
          that.editSave()
        } else {
          that.addSave()
        }
      }
    },

    // 编辑保存
    editSave() {
      const that = this

      const variables = { ...this.formField }
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: {
          ServiceCode: 'updateParts',
          APIUrl: '/mp/e3sh/spareparts/listMaintenanceService/updateParts.do'
        },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables

      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: this.$t('sys.tips.esTip5') /* 保存成功*/,
            type: 'success',
            duration: 1000
          })
          this.closeEdit()
          this.$parent.queryTable(1)
        } else {
          // 保存失败
          this.$message({
            message:
              '保存失败:' + response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    // 新增保存
    addSave() {
      const that = this
      const variables = this.$utils.deepCopy(this.formField)
      variables.partNo = this.$store.state.user.orgInfo.DLR_CODE + variables.partNo
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: orgApis.maintenanceOfSparePartsListOfOutletsaddsave,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: '添加成功',
            type: 'success',
            duration: 1000
          })
          this.curPopupsVisible = false
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message({
            message:
              '添加失败:' + response.msg,
            type: 'warn',
            uration: 1000
          })
        }
        this.curPopupsVisible = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.promptSpan{
  position: absolute;
  bottom: 26px;
  right: 335px;
  color: #e70020;
}
</style>

